package cn.boodqian.d3surveyor;

import java.lang.reflect.Type;
import java.util.HashMap;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.boodqian.util.ServerMessageTask;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import cn.boodqian.util.Log;
import android.view.View;
import android.view.Window;

public class D3SurveyorActivity extends D3Activity {
	class ServerMessage {
		private int version;
		private String update;
		private String message;
		private int messagecode;
	}
	class ServerMessageHandler extends Handler {

		/* (non-Javadoc)
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {
			HashMap<String,String> map = null;
			try {
				Type type = new TypeToken<HashMap<String,String>>(){}.getType();
				map = m_Gson.fromJson(msg.obj.toString(), type);
			} catch(Exception e) {
				map = null;
				e.printStackTrace();
			}
			if(map==null || map.size()==0) {
				Log.w("Received invalid update message");
				return;
			}
			
			Log.i("Received: "+map.toString());
			
			String message = null;
			String title = null;

			int savedLastServerMessageCode = m_LastServerMessageCode;
			long savedLastUpdateMessageTime = m_LastUpdateMessageTime;
			long now = System.currentTimeMillis();

			try {
				int currentVersion = m_PackageInfo.versionCode;
				int messageVersion = Integer.parseInt(map.get("version"));

				Log.i(String.format("Server Message version=%d current=%d)", messageVersion, currentVersion));

				if(currentVersion > messageVersion) return;


				if(currentVersion < messageVersion) {
					// When version below, show 'update' field
					title = D3SurveyorActivity.this.getString(R.string.server_update);
					message = map.get("update");

					// Only display update message once a day
					if(isSameDay(m_LastUpdateMessageTime, now)) return;
					m_LastUpdateMessageTime = now;
				} else {
					int messagecode = Integer.parseInt(map.get("messagecode"));
					Log.i(String.format("messagecode: old %d new %d", m_LastServerMessageCode, messagecode));

					// When version matches, show 'message' field
					title = D3SurveyorActivity.this.getString(R.string.server_message);
					message = map.get("message");

					// Only display message with higher code
					if(m_LastServerMessageCode >= messagecode) return;
					m_LastServerMessageCode = messagecode;
				}
			} catch(Exception e) {
				Log.e("Server message parse error");
				e.printStackTrace();
				m_LastServerMessageCode = savedLastServerMessageCode;
				m_LastUpdateMessageTime = savedLastUpdateMessageTime;
				return;
			}
			if(message==null || message.compareTo("")==0) return;

			Intent intent = new Intent(D3SurveyorActivity.this, ServerMessageActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent.putExtra("title", title);
			intent.putExtra("message", message);
			PendingIntent contentIntent = PendingIntent.getActivity(D3SurveyorActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );
			Notification notification = new Notification(R.drawable.ic_launcher, title, now);
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			NotificationManager nm = (NotificationManager) D3SurveyorActivity.this.getSystemService(NOTIFICATION_SERVICE);
			notification.setLatestEventInfo(D3SurveyorActivity.this, title, message, contentIntent);

			nm.notify(1, notification);
		}

		private boolean isSameDay(long a, long b) {
			return (a/86400000 == b/86400000);
		}
	}
	
	Gson m_Gson = new Gson();
    private Handler m_Handler = new ServerMessageHandler();
	private int m_LastServerMessageCode = 0;
	private long m_LastUpdateMessageTime = 0;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.main);
        
        m_DB = D3DB.getNewInstance(this);
        m_Back.setText(getString(R.string.quit));
        
        restorePrefs();
    }

	@Override
	protected void onStart() {
		super.onStart();
		
		new ServerMessageTask(m_Handler).execute(getString(R.string.update_url));
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		savePrefs();
	}

	private void restorePrefs()
	{
		SharedPreferences prefs = getPreferences(MODE_PRIVATE);
		String version = prefs.getString("version", "");
		if(m_PackageInfo.versionName.compareTo(version) != 0) {
			Log.i(String.format("Version names (%s vs %s) do not match", version, m_PackageInfo.versionName));
			return;
		}
		m_LastServerMessageCode = prefs.getInt("last_server_message_code", 0);
		m_LastUpdateMessageTime = prefs.getLong("last_update_message_time", 0);
	}
	
	private void savePrefs()
	{
		SharedPreferences prefs = getPreferences(MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putString("version", m_PackageInfo.versionName);
		editor.putInt("last_server_message_code", m_LastServerMessageCode);
		editor.putLong("last_update_message_time", m_LastUpdateMessageTime);
		editor.commit();
	}
}